package br.com.menosehmais.framework.security;

////import br.com.menosehmais.framework.security.holder.SessionAuthenticationHolder;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.menosehmais.framework.presentation.RestResponseController;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

//@Intercepts(after={JPATransactionInterceptor.class})
@RequestScoped
public class AuthenticationInteceptor implements Interceptor {

    protected final HttpServletRequest request;
    protected UserSession userSession;
    protected Result result;
    protected final Logger logger = Logger.getLogger(this.getClass());

    public AuthenticationInteceptor(Result result, HttpServletRequest request,
            UserSession userSession) {
        this.request = request;
        this.userSession = userSession;
        this.result = result;
    }

    @Override
    public boolean accepts(ResourceMethod method) {
        return true;
    }

    @Override
    public void intercept(InterceptorStack stack,
                          ResourceMethod method,
                          Object resourceInstance) {

        if (SecurityHandler.canExecute(userSession.getAccountInfo(), method.getResource().getType(), method.getMethod())) {
            stack.next(method, resourceInstance); // continua executando
        } else {
            
            // Usuario nao logado
            if (!userSession.isLogged()) {
                // extract the receiving URL from the HTTP request
                StringBuffer receivingURL = request.getRequestURL();
                
                if( receivingURL.toString().contains("/rest/") ){ // É uma requisicao rest!
                
                    logger.info("Usuario nao logado tentou acessar REST " + receivingURL.toString() + ". Acesso Negado ");
    
                    result.forwardTo(RestResponseController.class).error("Permissão negada. Usuário não autenticado.");
                    
                }else{ // Requisição http normal

                    String queryString = request.getQueryString();
                    if (queryString != null && queryString.length() > 0) {
                        receivingURL.append("?").append(queryString);
                    }
                    
                    logger.info("Usuario nao logado tentou acessar "
                            + receivingURL.toString()
                            + " Redirecionando para "
                            + "/ssl/loginForm");
    
                    result.include("path", receivingURL)
                          .forwardTo(LoginController.class).loginForm();
                }
                
            } else { //Usuario logado
                
                stack.next(method, resourceInstance); // continua a executado
            }
        }
    }
}